package org.travel.app.controller.manage;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.travel.app.common.util.UploadUtil;
import org.travel.app.common.vo.ResultVO;
import org.travel.app.controller.BaseController;
import org.travel.app.entity.spots.Spots;
import org.travel.app.entity.spots.SpotsImag;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author nmm
 * @date 2024-11-2024/11/14
 * @deriction 单个图片上传(minio存储)
 */
@RestController
public class UploadController extends BaseController {
    @Autowired
    private MinioClient minioClient;

    /**
     * 使用 ConcurrentHashMap 作为临时存储
     */
    private final Map<String, List<String>> scenicImages = new ConcurrentHashMap<>();

    @Autowired
    private RedisTemplate<String,List<String>> listRedisTemplate;

    @PostMapping("/upload/{path}")
    public String upload(@PathVariable("path") String prefix,@RequestParam(value = "path2", required = false) String prefix2,@RequestParam(value = "spotsId", required = false) String spotsId,@RequestParam("files") MultipartFile[] files) {
        AtomicReference<String> fileNameRef = new AtomicReference<>(null);
        List<String> fileNames=new ArrayList<>();
        Arrays.stream(files).forEach(file -> {
            try {
                InputStream inputStream=file.getInputStream();
                String fileName=UUID.randomUUID()+ UploadUtil. getFileSuffix(file);
                fileNameRef.set(fileName);
                fileNames.add(prefix2.isEmpty()?fileName:prefix2+"/"+fileName);
                //加上文件夹路径
                minioClient.putObject(
                        PutObjectArgs.builder().bucket("image")
                                .object(prefix2.isEmpty()?prefix+"/"+fileName:prefix + "/" + prefix2 + "/" + fileName)
                                .stream(inputStream,file.getSize(),-1)
                                .contentType(file.getContentType())
                                .build()
                );
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        try {
            uploadImages(spotsId,fileNames);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //保存图片到缓存
        return prefix2==null?fileNameRef.get():"Success";
    }

    /**
     * 将图片保存到缓存
     * @param spotsId
     * @param list
     * @throws IOException
     */
    public void uploadImages(String spotsId,List<String> list) throws IOException {
        scenicImages.put(spotsId, list);
        //临时存储
        listRedisTemplate.opsForHash().put("scenicImages", spotsId,list);
        //将图像列表存入 Redis Hash
    }


    /**
     * 取出图片列表
     * @param spots
     * @return
     */
    @PostMapping("/getSpotsImages")
    public ResultVO getImages(@RequestBody Spots spots) {
        String spotId=spots.getSpotId().toString();
        List<String> spotsImages =scenicImages.getOrDefault  (spotId,(List<String>)listRedisTemplate.opsForHash().get("scenicImages",spotId)) ;
        return success(spotsImages);
    }

}